import {
	defineStore
} from 'pinia';
import http from '../common/request'
import useUserStore from './userStore';
import {
	compareDates,
	formatDate,
	parseDate
} from '../utils';

export default defineStore('configStore', {
	state: () => {
		return {
			webrtc: {},
			/**
			 * 行为缓存
			 */
			behavior: {},
			/**
			 * 显示分享框
			 */
			sharePanelShow: false,
			shareCode: null
		}
	},
	actions: {
		showSharePanel(shareCode) {
			this.sharePanelShow = true
			this.shareCode = shareCode
		},
		closeSharePanel() {
			this.sharePanelShow = false
			this.shareCode = null
		},
		setConfig(config) {
			this.webrtc = config.webrtc;
		},
		clear() {
			this.webrtc = {};
		},
		loadConfig() {
			// 加载缓存配置
			this.behavior = uni.getStorageSync("behavior") || {}
			return new Promise((resolve, reject) => {
				http({
					url: '/system/config',
					method: 'GET'
				}).then((config) => {
					// console.log("系统配置", config)
					this.setConfig(config);
					resolve();
				}).catch((res) => {
					reject(res);
				});
			})
		},
		/**设置行为验证缓存
		 * @param {Object} key
		 * @param {Object} value
		 */
		setBehavior(key, value) {
			const userId = useUserStore().userInfo.id;
			let behaviorStorage = uni.getStorageSync("behavior")
			if (!behaviorStorage) {
				behaviorStorage = {}
			}
			if (!behaviorStorage[userId]) {
				behaviorStorage["user-" + userId] = {}
			}
			behaviorStorage["user-" + userId][key] = {
				value: value
			}
			this.behavior = behaviorStorage
			uni.setStorageSync("behavior", this.behavior)
		},
		/**设置行为验证缓存过期时间
		 * @param {Object} key
		 * @param {Object} value
		 * @param {Number} expires 过期时间
		 */
		setBehaviorExpires(key, value, expires) {
			this.behavior = uni.getStorageSync("behavior")
			const userId = useUserStore().userInfo.id;
			/* if (!this.behavior[userId]) {
				this.behavior[userId] = {}
			} */
			const data = {}
			data["user-" + userId] = {}
			data["user-" + userId][key] = {
				value: value,
				expires: formatDate(new Date(new Date().getTime() + expires), "yyyy-MM-dd HH:mm-ss")
			}
			this.behavior = {
				...this.behavior,
				...data
			}

			// this.behavior[userId][key] = {
			// 	value: value,
			// 	expires: formatDate(new Date(new Date().getTime() + expires), "yyyy-MM-dd HH:mm-ss")
			// }
			uni.setStorageSync("behavior", this.behavior)
		},
		/**获取指定行为的值
		 * @param {Object} key
		 */
		getBehavior(key) {
			this.behavior = uni.getStorageSync("behavior")
			const userId = "user-" + useUserStore().userInfo.id;
			if (this.behavior[userId] && this.behavior[userId][key] && (!this.behavior[userId][key]
					.expires || (this.behavior[userId][key].expires && compareDates(parseDate(this.behavior[
						userId][key].expires), new Date()) == 1))) {
				return this.behavior[userId][key].value
			}
			return null
		},
		/**获取指定行为的布尔值
		 * @param {Object} key
		 */
		getBehaviorBool(key) {
			return this.getBehavior(key) && true || false
		},
	}
})